package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;

import com.example.authforcmcc.AuthForCmcc;
import com.example.authforcmcc.Global;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class WebauthTestWidgetProxy extends GeneralTestWidget {

	private Activity ctx;
	private Handler handlerChild;
	private final Handler handler;
	private WebAuthManager webAuthManager;
	private WlanManager wlanManager;
	private Button btnback;
	private Button btnRetest;
	private int frequency;
	private int current;
	private String defaultUrl;
	private boolean processing;
	private float loginTotalTime;
	private int lsuccessTimes;
	private int osuccessTimes;
	private float logoutTotalTime;
	private static String TAG = "WebauthTestWidget";
	private EditText userNameEt;
	private EditText pwdEt;
	private Button btnStart;
	private int testedTimes;
	private static String username;
	private static String password;
	private Task task;
	public static int testFlag = 0;
	public static int taskFlag = 0;
	private boolean isFirst = true;
	private boolean logouting = false;
	
	private AuthForCmcc authForCmcc;
	private boolean loginSucess;

	public WebauthTestWidgetProxy(Activity context, Handler handl) {
		super(context);
		this.ctx = context;
		this.handlerChild = handl;
		inflate(context, R.layout.webauth_test_widget_proxy, this);
		btnback = (Button) this.findViewById(R.id.webauth_test_proxy_btnback);
		defaultUrl = ctx.getResources().getString(R.string.default_url);
		userNameEt = (EditText) this.findViewById(R.id.userNameEditTextProxy);
		pwdEt = (EditText) this.findViewById(R.id.pwdEditTextProxy);
		btnStart = (Button) this.findViewById(R.id.btn_webauth_proxy_start);
		btnback.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backToTask(ctx);
			}
		});

		btnStart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				start();
			}
		});

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.DO_NEXT_TEST:
					// showNextText();
					break;
				 case MessageWhat.WEB_AUTH_LOGIN:
	                	if (current<frequency) {
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							current ++;
							webAuthManager.setStartTime(System.currentTimeMillis());
							authForCmcc.startAuth();
						}else {
							handler.sendEmptyMessage(MessageWhat.DONE);
						}
	                	break;
	                case MessageWhat.WEB_AUTH_LOGOUT:
	                	webAuthManager.setStartTime(System.currentTimeMillis());
	                	if (loginSucess) {
							authForCmcc.logoutcmcc();
						}else {
							handler.sendEmptyMessage(MessageWhat.LOGOUT_FAILED);
						}
	                	break;
				default:
					update(msg.what);
				}
			}
		};
		DBManager db = new DBManager(ctx);
		Account config = db.getAccount();
		if (null != config) {
			username = config.userName;
			password = config.password;
		}
		db.release();
		webAuthManager = new WebAuthManager(ctx);
		webAuthManager.setHandler(handler);
		wlanManager = new WlanManager(ctx);
		wlanManager.setHandler(handler);
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
		frequency = task.testCount;
		start();
		// scanWifi();
	}

	/*
	 * private void scanWifi() { this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
	 * new Thread() { public void run() { wlanManager.startScan(); } }.start();
	 * }
	 * 
	 * private void enableNetWork(final ScanResult scan) {
	 * this.showMessageDialog(ctx, "正在连接Wifi..."); new Thread() { public void
	 * run() { wlanManager.connect(scan); } }.start();
	 * 
	 * }
	 */

	private void update(int what) {
		// ----------------------------------------------------------
		if (isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_WEB_test = temp;
		}
		// ----------------------------------------------------------
		testedTimes++;
		webAuthManager.setEndTime(System.currentTimeMillis());
		this.setDialogProgress(testedTimes);
		StringBuffer s = new StringBuffer();
		float costTime = (webAuthManager.getEndTime() - webAuthManager
				.getStartTime()) / (float) 1000;
		if (MessageWhat.LOGIN_SUCCESS == what) {
			s.append("第").append(current).append("次 登录成功，时延：").append(costTime)
					.append('s');
			// ----------------------------------------------------------

			GlobalApp.result_WEB_test.append("第").append(current)
					.append("次 登录成功，时延：").append(costTime).append("s\n");

			// ----------------------------------------------------------
			loginTotalTime += costTime;
			lsuccessTimes++;
			loginSucess = true;
			handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGOUT);
		} else if (MessageWhat.LOGOUT_SUCCESS == what) {
			s.append("第").append(current).append("次 下线成功，时延：").append(costTime)
					.append('s');
			s.append("第").append(current).append("次 下线成功，时延：").append(costTime)
					.append('s');
			// ----------------------------------------------------------

			GlobalApp.result_WEB_test.append("第").append(current)
					.append("次 下线成功，时延：").append(costTime).append("s\n");

			// ----------------------------------------------------------
			logoutTotalTime += costTime;
			osuccessTimes++;
			handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGIN);
		} else if (what == MessageWhat.LOGIN_FAILED) {
			s.append("第").append(current).append("次 登录失败");
			s.append("第").append(current).append("次 登录失败");
			// ----------------------------------------------------------
			GlobalApp.result_WEB_test.append("第").append(current)
					.append("次 登录失败\n");
			// ----------------------------------------------------------
			// showMessage(ctx, "web认证第"+current+"次登录失败");
			loginSucess = false;
			handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGOUT);
		} else if (what == MessageWhat.LOGOUT_FAILED) {
			s.append("第").append(current).append("次 下线失败");
			// ----------------------------------------------------------

			GlobalApp.result_WEB_test.append("第").append(current)
					.append("次 下线失败\n");

			// ----------------------------------------------------------
			// showMessage(ctx, "web认证第"+current+"次下线失败");
			handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGIN);
		}
		if (MessageWhat.DONE == what) {
			DecimalFormat df = new DecimalFormat("#0.000");
			float lavg = (lsuccessTimes == 0) ? 0 : loginTotalTime
					/ (float) lsuccessTimes;
			if (lavg == 0) {
				lavg = (osuccessTimes == 0) ? 0 : loginTotalTime
						/ (float) osuccessTimes;
			}

			// long oavg = (osuccessTimes == 0) ? 0 : logoutTotalTime /
			// osuccessTimes;
			float sucessRate = ((float) lsuccessTimes / frequency) * 100;
			float offSuccessRate = ((float) osuccessTimes / frequency) * 100;
			s = new StringBuffer();
			s.append("认证次数：").append(frequency).append("次; ");
			s.append("成功次数：").append(lsuccessTimes).append('次').append('\n');
			s.append("认证平均时延：").append(df.format(lavg)).append('s')
					.append('\n');
			s.append("认证成功率：").append(sucessRate).append('%').append(" 下线成功率：")
					.append(offSuccessRate).append('%');
			// ----------------------------------------------------------

			GlobalApp.result_WEB_test.append("\n认证次数：").append(frequency)
					.append("次").append("\n成功次数：").append(lsuccessTimes)
					.append("次").append("\n认证平均时延：").append(df.format(lavg))
					.append("s").append("\n认证成功率：").append(sucessRate)
					.append("%").append("\n下线成功率：").append(offSuccessRate)
					.append("%\n");
			;

			// ----------------------------------------------------------

			task.endTime = StringUtils.getDateTime();
			task.webDelay = String.valueOf(df.format(lavg));
			task.webSuccessRate = String.valueOf(sucessRate);
			task.webOffSuccessRate = String.valueOf(offSuccessRate);

			task.webLoginCount = task.testCount + "";
			task.webLoginSuccessCount = lsuccessTimes + "";
			task.webOutCount = task.testCount + "";
			task.webOutSuccessCount = osuccessTimes + "";

			System.out.println("task.webLoginCount => " + task.webLoginCount);
			System.out.println("task.webLoginSuccessCount => "
					+ task.webLoginSuccessCount);
			System.out.println("task.webSuccessRate => " + task.webSuccessRate);
			System.out.println("task.webOutCount => " + task.webOutCount);
			System.out.println("task.webOutSuccessCount => "
					+ task.webOutSuccessCount);
			System.out.println("task.webOffSuccessRate => "
					+ task.webOffSuccessRate);
			System.out.println("task.webDelay => " + task.webDelay);

			ctx.getIntent().putExtra(TAG_REFER_TASK, task);

			dismissProgressDialog();
			Global.AuthString = null;
			handlerSendToTarget(handlerChild, MessageWhat.HANDLER_WEB);
		}
		processing = false;
	}

	private void clear() {
		testedTimes = 0;
		current = 0;
		loginTotalTime = 0;
		logoutTotalTime = 0;
		lsuccessTimes = 0;
		osuccessTimes = 0;
		processing = false;
	}

	public void start() {
		 
		clear();
		authForCmcc = new AuthForCmcc(ctx, handler, username, password);
		
		new Thread() {
			public void run() {
				boolean success = webAuthManager.logout2();
				if (GlobalApp.canUse ) {
					handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGIN);
				}else {
					handler.sendEmptyMessage(MessageWhat.DONE);
				}
				
			}
		}.start();
	}

	private void printInfo(boolean b, boolean login) {
		if (login) {
			if (b) {
				System.out.println("------ 认证 成功");
			} else {
				System.out.println("------ 认证 失败");
			}
		} else {
			if (b) {
				System.out.println("------ 下线 成功");
			} else {
				System.out.println("------ 下线 失败");
			}
		}
	}
//
//	private void lastWebAuth() {
//		new Thread() {
//			public void run() {
//				try {
//					Thread.sleep(500);
//				} catch (InterruptedException e) {
//					Log.e(TAG, "WEB登录下线时线程等待出错：", e);
//				}
//				boolean b = webAuthManager.auth(defaultUrl, username, password);
//				printInfo(b, true);
//				handlerSendToTarget(handlerChild, MessageWhat.HANDLER_WEB);
//			}
//		}.start();
//	}
}
